/**
 * 
 */
package com.miolr.core.dao.hibernate;

import org.hibernate.cfg.ImprovedNamingStrategy;

/**
 * @author iday
 * 
 */
public class PrefixedNamingStrategy extends ImprovedNamingStrategy {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4866924586961901400L;
	private static final String DEFAULT_PREFIX = "mio_";

	private String prefix = DEFAULT_PREFIX;

	public PrefixedNamingStrategy() {
		super();
	}

	public PrefixedNamingStrategy(String prefix) {
		super();
		this.prefix = prefix;
	}

	/**
	 * @param prefix
	 *            the prefix to set
	 */
	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}

	/**
	 * @return the prefix
	 */
	public String getPrefix() {
		return prefix;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.hibernate.cfg.ImprovedNamingStrategy#classToTableName(java.lang.String
	 * )
	 */
	@Override
	public String classToTableName(String className) {
		String tableName = super.classToTableName(className);
		switch (tableName.charAt(tableName.length() - 1)) {
		case 'y':
			tableName = tableName.substring(0, tableName.length() - 1) + "ie";
			break;
		case 'c':
			tableName = tableName.substring(0, tableName.length() - 1) + "ce";
			break;
		case 's':
			tableName = tableName.substring(0, tableName.length() - 1) + "se";
			break;
		}
		tableName = this.prefix + tableName + "s";
		return tableName;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.hibernate.cfg.ImprovedNamingStrategy#collectionTableName(java.lang
	 * .String, java.lang.String, java.lang.String, java.lang.String,
	 * java.lang.String)
	 */
	@Override
	public String collectionTableName(String ownerEntity,
			String ownerEntityTable, String associatedEntity,
			String associatedEntityTable, String propertyName) {
		return super.collectionTableName(ownerEntity, ownerEntityTable,
						associatedEntity, associatedEntityTable, propertyName);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.hibernate.cfg.ImprovedNamingStrategy#foreignKeyColumnName(java.lang
	 * .String, java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public String foreignKeyColumnName(String propertyName,
			String propertyEntityName, String propertyTableName,
			String referencedColumnName) {
		return super.foreignKeyColumnName(propertyName, propertyEntityName,
				propertyTableName, referencedColumnName) + "_id";
	}

	@Override
	public String tableName(String tableName) {
		return this.prefix + super.tableName(tableName);
	}

}
